package com.hxc.web.controller.common;

import cn.hutool.core.util.ObjectUtil;
import com.hxc.common.config.MinioConfig;
import com.hxc.common.core.domain.AjaxResult;
import com.hxc.common.utils.minio.MinioServiceUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/files")
@Api(tags = "Minio文件服务")
public class MinioFileController {

    @Autowired
    private MinioServiceUtil minioService;

    @Resource
    private MinioConfig minioConfig;

    /**
     * 上传文件
     *
     * @param file 文件
     * @return
     */
    @ApiOperation(value = "上传文件")
    @PostMapping("/upload")
    public AjaxResult upload(MultipartFile file) {
        try {
            if (file != null && !file.isEmpty()) {
                Map<String, String> map = minioService.putObject(minioConfig.getBucketDefaultName(), file);
                if (map == null) {
                  return AjaxResult.error("上传失败，请重新上传");
                }
                return AjaxResult.success("文件上传成功", map);
            } else {
                return AjaxResult.error("请传入文件");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return AjaxResult.error(ex.getMessage());
        }
    }


    /**
     * 多文件上传
     *
     * @param file 文件
     * @return
     */
    @ApiOperation(value = "多文件上传")
    @PostMapping("/moreUpload")
    public AjaxResult moreUpload(@RequestParam("avatarfile") List<MultipartFile> file) {
        List<String> list = new ArrayList<>();
        try {
            if (file != null && !file.isEmpty()) {
                file.forEach((var)->{
                    Map<String, String> map = minioService.putObject(minioConfig.getBucketDefaultName(), var);
                    if (ObjectUtil.isNotNull(map)){
                        list.add(map.get("objectUrl"));
                    }
                });
                if (list != null || list.size()>0) {
                    return AjaxResult.success("文件上传成功", list);
                }else {
                    return AjaxResult.error("上传失败，请重新上传");
                }
            } else {
                return AjaxResult.error("请传入文件");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return AjaxResult.error(ex.getMessage());
        }
    }


    /**
     * 下载附件
     * objectName = dateDir +"/"+fileName;
     *
     * @param bucketName 桶名称
     * @param dateDir    时间目录
     * @param fileName   文件名
     * @return
     * @throws UnsupportedEncodingException
     */
    @ApiOperation(value = "下载附件")
    @GetMapping("/download/{bucketName}/{dateDir}/{fileName}")
    public void downloadFile(@PathVariable String bucketName, @PathVariable String dateDir, @PathVariable String fileName, HttpServletResponse response) {
        if (bucketName == null || fileName == null || dateDir == null) {
            return;
        }
        String objectName = dateDir + "/" + fileName;
        minioService.downloadObject(bucketName, objectName, response);
    }

    /**
     * 删除附件
     * objectName = dateDir +"/"+fileName;
     *
     * @param bucketName 桶名称
     * @param dateDir    时间目录
     * @param fileName   文件名
     * @return
     */
    @GetMapping("/delete/{bucketName}/{dateDir}/{fileName}")
    public AjaxResult deleteFile(@PathVariable String bucketName, @PathVariable String dateDir, @PathVariable String fileName) {
        if (bucketName == null || fileName == null || dateDir == null) {
            return AjaxResult.error("请传入正确参数");
        }
        String objectName = dateDir + "/" + fileName;
        boolean flag = minioService.removeObject(bucketName, objectName);
        if(flag){
            return AjaxResult.success("文件删除成功");
        }else{
            return AjaxResult.error("文件删除失败");
        }
    }

}
